#include <iostream>
#include <unistd.h>
#include <vector>
#include <pthread.h>
int g_tickets = 10000; //票数 ... 共享资源
__thread int thread_tickets = 0; //记录当前线程抢到的票数

std::vector<int> result;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;//定义一把锁

void* route(void* args)
{
    int thread_tickets = 0; //每个线程抢的票数
    //模拟抢票逻辑
    while(true)
    {
        pthread_mutex_lock(&mutex);//加锁
        if(g_tickets > 0)
        {
            usleep(1000);
            g_tickets--;
            pthread_mutex_unlock(&mutex);//解锁
            thread_tickets++;
        }
        else 
        {
            std::cout << "I am new thread , I snap up tickets = " << thread_tickets << std::endl;//统计当前进程抢到的票数
            pthread_mutex_unlock(&mutex);//解锁
            break;
        }
    }  
}
int main()
{
    std::vector<pthread_t> threads;
    //1、创建线程
    for(size_t i = 0 ; i < 5 ; ++i)
    {
        pthread_t tid;
        pthread_create(&tid,nullptr,route,nullptr);
        threads.push_back(tid);
    }
    //2、等待线程
    for(auto& thread : threads)
    {
        pthread_join(thread,nullptr);
    }
    std::cout << "tickets = " << g_tickets << std::endl;
    return 0;
}
